package cn.fang2chen.java.distributed.lock.framework.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

import java.util.Collections;

/**
 *
 * @author dcmini chen
 * @since 1.0.0
 */
public class JedisRedisClient implements RedisClient {

    /**
     * 连接池
     */
    private final JedisPool jedisPool;

    public JedisRedisClient(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Override
    public boolean setNxPx(String key, String value, long expired) {
        Jedis jedis = jedisPool.getResource();
        try {
            SetParams params = SetParams.setParams().nx().px(expired);
            String lock = jedis.set(key, value, params);
            return "OK".equals(lock);
        } finally {
            jedis.close();
        }

    }

    @Override
    public boolean delCas(String key, String expect) {
        Jedis jedis = jedisPool.getResource();
        try {
        String script =
                "if redis.call('get',KEYS[1]) == ARGV[1] then" +
                        "   return redis.call('del',KEYS[1]) " +
                        "else" +
                        "   return 0 " +
                        "end";
        Object result = jedis.eval(script, Collections.singletonList(key),
                Collections.singletonList(expect));
//        System.out.println(String.format("delCas %s, %s, %s", key, expect, result.toString()));
        return "1".equals(result.toString());
        } finally {
            jedis.close();
        }
    }

    @Override
    public boolean hasValue(String key) {
        Jedis jedis = jedisPool.getResource();
        try {
            String value = jedis.get(key);
            return value != null;
        } finally {
            jedis.close();
        }
    }

    @Override
    public String getValue(String key) {
        Jedis jedis = jedisPool.getResource();
        try {
            String value = jedis.get(key);
            return value;
        } finally {
            jedis.close();
        }
    }

    @Override
    public long timeRemaining(String key) {
        Jedis jedis = jedisPool.getResource();
        try {
            return jedis.pttl(key);
        } finally {
            jedis.close();
        }

    }

}
